package com.example.emergencyattempt01.activity.utils;

import org.json.JSONException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class NetWorkUtils extends AbstractNetWorkUtils {
    private  static String myServerHome="http://106.52.102.86:8080";
    private  static String serviceContext="/connect02";
    private static NetWorkUtils instance=new NetWorkUtils();

    private NetWorkUtils()
    {
    }

    public static NetWorkUtils getInstance() {
        return instance;
    }

    // 以下方法用于创建一个连接
    protected HttpURLConnection build_connection(String service) throws IOException// 直接抛出异常至上层去
    {
        HttpURLConnection connection=null;
        URL url;
        url=new URL(myServerHome+serviceContext+service);
        connection=(HttpURLConnection) url.openConnection();
        // 为这个connection设置各种共同的初始属性
        connection.setRequestProperty("Content-Type","application/json");
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoInput(true);
        connection.setReadTimeout(11000);

        return connection;
    }


    protected int sendRequest(String toServer,HttpURLConnection connection) throws JSONException,IOException{
        // 创建输出流
        OutputStream outputStream=connection.getOutputStream();
        // 对待发送的字符串进行编码,不为空则编，为空，忽略此步骤
        if(toServer!=null)
        {
            toServer= URLEncoder.encode(toServer,"utf-8");
            // 发送数据流
            outputStream.write(toServer.getBytes());
        }
        // 返回服务器返回的返回码
        int code=connection.getResponseCode();
        outputStream.close();
        return  code;
    }

    protected String getRespond(HttpURLConnection connection)throws JSONException,IOException {
        InputStream inputStream=connection.getInputStream();
        ByteArrayOutputStream outputStreamBack=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];
        int len=-1;
        while((len=inputStream.read(buffer))!=-1)
        {
            outputStreamBack.write(buffer,0,len);
        }
        // 读取流得到返回而来的字符串
        String fromServer=new String(outputStreamBack.toByteArray());
        // 进行解码
        fromServer= URLDecoder.decode(fromServer,"utf-8");
        inputStream.close();
        outputStreamBack.close();
        return  fromServer;
    }

    // 既发送又返回的服务
   /* private  ServerMessage sendRequestWithRespond(String toServer, String service)throws JSONException,IOException
    {
        //创建一个网络连接
        HttpURLConnection connection=build_connection(service);
        // 调用请求方法，返回请求码
        int code=sendRequest(toServer,connection);
        // 调用获取响应方法，得到服务器发来的字符串（已解码）
        String fromServer=getRespond(connection);

        // 打包信息，返回给调用者
        ServerStringMessage message=new ServerStringMessage();
        message.setRespondCode(code);
        message.setFromServer(fromServer);
        return message;
    }*/
    // 不发送只返回的服务
   /* private static ServerMessage simplyRespond(String service)throws JSONException,IOException
    {
        // 创建一个网络请求
        HttpURLConnection connection=build_connection(service);
        // 调用获取响应的方法，得到服务器发来的字符串
        String fromServer=getRespond(connection);
        // 得到返回码，但基本用不上
        int code=connection.getResponseCode();
        ServerStringMessage serverMessage=new ServerStringMessage();
        serverMessage.setRespondCode(code);
        serverMessage.setFromServer(fromServer);
        return serverMessage;
    }*/
    // 只发送不返回的服务
   /* private  static ServerMessage sendRequestWithoutRespond(String toServer, String service)throws JSONException,IOException
    {

        // 创建一个连接
        HttpURLConnection connection=build_connection(service);
        // 调用请求方法，得到请求的返回码
        int code= sendRequest(toServer,connection);
        Log.i("toServer",toServer);
        // 将信息打包返回给调用者
        ServerStringMessage message=new ServerStringMessage();
        message.setRespondCode(code);
        return message;
    }*/
    // 原版
   /*    // 查询所有用户的功能
    public static ServerMessage queryAllUser()throws JSONException,IOException
    {
      return simplyRespond("/query_all_user");
    }
   // 添加用户功能
    public  static ServerMessage addNewUser(String toServer) throws JSONException,IOException
    {
        return sendRequestWithoutRespond(toServer,"/add_new_user");
    }
    // 查人功能，提供关键词及类型，返回查询结果
    public static ServerMessage searchUser(String toServer)throws JSONException,IOException
    {
        return sendRequestWithRespond(toServer,"/search_user");
    }
    public static ServerMessage deleteUser(String toServer)throws JSONException,IOException
    {
        return sendRequestWithoutRespond(toServer,"/delete_user");
    }
    public static ServerMessage updateUser(String toServer)throws JSONException,IOException
    {
        return sendRequestWithoutRespond(toServer,"/update_user");
    }
    public static ServerMessage findAllBorrowing() throws JSONException,IOException
    {
        return simplyRespond("/find_all_borrowing");
    }*/

    // 提取出来的一个工厂方法
  /*  @Override
    public ServerMessage create( String toServer, String service) throws IOException,JSONException{
        // 各种与用户信息相关的网络操作产生的message
        // 以下，如果新的设计模式成功了，可以当作反面教材，没成功的话，就维持现状吧...
        /*
        if(service.equals("/query_all_user"))
            return simplyRespond(service);
        else if (service.equals("/add_new_user"))
            return sendRequestWithoutRespond(toServer,service);
        else if(service.equals("/search_user"))
            return sendRequestWithRespond(toServer,service);
        else if (service.equals("/delete_user"))
            return sendRequestWithRespond(toServer,service);
        else if(service.equals("/update_user"))
            return sendRequestWithoutRespond(toServer,service);

        // 各种借阅相关的操作产生的message
        // 所有正常再借和已归还记录
        else if(service.equals("/find_all_borrowing"))
            return simplyRespond(service);
        // 拒绝借书
        else if(service.equals("/borrow_book_refuse"))
            return sendRequestWithoutRespond(toServer,service);
        // 同意借书
        else if(service.equals("/borrow_book_permit"))
            return sendRequestWithRespond(toServer,service);
        // 拒绝还书
        else if(service.equals("/return_book_refuse"))
            return sendRequestWithoutRespond(toServer,service);
        // 同意还书
        else if(service.equals("/return_book_permit"))
            return sendRequestWithoutRespond(toServer,service);
        // 拒绝续借
        else if(service.equals("/continue_refuse"))
            return sendRequestWithoutRespond(toServer,service);
        // 同意续借
        else if(service.equals("/continue_permit"))
            return sendRequestWithoutRespond(toServer,service);
        // 加载待管理员处理的所有请求
        else if(service.equals("/find_requesting"))
            return simplyRespond(service);
        // 加载当前用户的所有请求中...
        else if(service.equals("/find_my_requesting"))
            return sendRequestWithRespond(toServer,service);

        // 管理员处理图书
        else if(service.equals("/search_all_book"))
            return simplyRespond(service);
        else if(service.equals("/search_by_keyword"))
            return sendRequestWithRespond(toServer,service);
        else if(service.equals("/update_book_info"))
            return sendRequestWithoutRespond(toServer,service);
        else if(service.equals("/update_stoke"))
            return sendRequestWithoutRespond(toServer,service);
        else if(service.equals("/delete_collection"))
            return sendRequestWithRespond(toServer,service);
        else if(service.equals("/add_new_book"))
            return sendRequestWithoutRespond(toServer,service);
        else if(service.equals("/find_all_type"))
            return simplyRespond(service);

        // 学生借阅/续借/还书请求发送
        else if(service.equals("/borrow_book_again"))// 被拒绝借书了，再借一次，审核中的操作
            return sendRequestWithoutRespond(toServer,service);
        else if(service.equals("/borrow_book_request")) //首次借书，在基本借书页搞的
            return sendRequestWithRespond(toServer,service);
        else if(service.equals("/cancel_borrow_request"))// 取消借阅，审核中，被拒绝后的一种选择
            return sendRequestWithoutRespond(toServer,service);
        else if(service.equals("/continue_cancel")) //取消续借
            return sendRequestWithoutRespond(toServer,service);
        else if(service.equals("/continue_request")) // 请求续借
            return sendRequestWithoutRespond(toServer,service);
        else if(service.equals("/return_book_cancel"))// 还书取消
            return sendRequestWithoutRespond(toServer,service);// 请求还书
        else if(service.equals("/return_book_request"))
            return sendRequestWithoutRespond(toServer,service);
        // 登录功能
        else if(service.equals("/login"))
            return sendRequestWithRespond(toServer,service);
        // 当前用户的在借书目查询
        else if(service.equals("/find_my_borrowing"))
            return sendRequestWithRespond(toServer,service);
        // 当前用户的历史记录查询
        else if(service.equals("/find_my_history"))
            return sendRequestWithRespond(toServer,service);

        return null;
        return sendRequestWithRespond(toServer,service);
    }*/
}
